const defaultImg = {};

defaultImg.install = (Vue) => {
  Vue.directive('default-img', async (el, binding) => {
    el.onerror = async () => {
      const imgURL = binding.value;
      if (imgURL) {
        const exist = await imageIsExist(imgURL);
        exist && el.setAttribute('src', imgURL);
      }
    };
  });
};

const imageIsExist = (url) => {
  return new Promise((resolve) => {
    let img = new Image();
    img.onload = function () {
      if (this.complete) {
        resolve(true);
        img = null;
      }
    };
    img.onerror = function () {
      resolve(false);
      img = null;
    };
    img.src = url;
  });
};

export default defaultImg;
